import mysql from 'mysql'
import { Models } from '../common/typings/model'
import dbConfig from '../config/dbConfig'

class Mysql {
    public static readonly pool = mysql.createPool({
        host: dbConfig.database.host,
        port: dbConfig.database.port,
        user: dbConfig.database.username, 
        password: dbConfig.database.password,
        database: dbConfig.database.dbName,
        connectionLimit : 1000,
        connectTimeout  : 60 * 60 * 1000,
        acquireTimeout  : 60 * 60 * 1000,
        timeout         : 60 * 60 * 1000,
    })

    /*
    * 数据库增删改查
    * @param command 增删改查语句
    * @param value 对应的值
    */
    public static query(command: string, value?: Array<any>):Promise<Models.Result>{
        return new Promise<Models.Result>(async (resolve,reject) =>{
            this.pool.getConnection((error: mysql.MysqlError, connection: mysql.PoolConnection)=>{
                //console.log(error,connection)
                if(error){
                    const result: Models.MysqlError = {
                        error,
                        message: "数据库连接出错",
                        name: 'mysql error'
                    } 
                    reject(result) 
                }
                const callback: mysql.queryCallback = (err, results?: any, fields?: mysql.FieldInfo[]) => {
                    //console.log(err)
                    connection.release();
                    if (err) {
                        let result: Models.MysqlError = {
                            error:err,
                            message: "数据库增删改查出错",
                            name: 'mysql error'
                        } 

                        reject(result);
                    } else {
                        let result: Models.Result = {
                            error:err,
                            message: "ok",
                            state: 1,
                            results,
                            fields: fields || []
                        } 
                        resolve(result);
                    }
                }
    
                if (value) {
                    this.pool.query(command, value, callback);
                } else {
                    this.pool.query(command, callback);
                }
            })
        }).catch(err=>{
            return {
                error:err,
                message: err.msg,
                state: 0,
                results:[],
                fields: []
            }
        })
    } 
}
export default Mysql


